import subprocess
import sys
import os
import json
import argparse
import requests
import warnings
import docker
import shlex

def try_web_access(port):
    url = "https://localhost:{}/UI/Rest/Login".format(port)
    retcode = -1
    session = requests.Session()
    session.trust_env = False
    try:
        with warnings.catch_warnings():
            warnings.simplefilter(
                "ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning)
            response = session.get(url, timeout=10, proxies={}, verify=False)
            retcode = response.status_code
    except requests.exceptions.RequestException as e:
        pass
    return retcode == 200

def read_config(config_path='config.json'):
    with open(config_path) as f:
        cfg = json.load(f)
    return cfg

def get_qemu_container():
    # 创建 Docker 客户端
    client = docker.from_env()
    
    # 获取所有运行的容器
    containers = client.containers.list()

    # 遍历容器，查找符合条件的容器
    target_containers_id = None
    for container in containers:
        # 检查容器名称和状态
        if 'qemu_container0' in container.name and container.status == 'running':
            target_containers_id = container.id
            print(f"✅ qemu启动成功, docker container id: {target_containers_id}, name: {container.name}, status: {container.status}")
            break
    
    if target_containers_id:
        return target_containers_id
    else:
        print("❌ No matching docker container found.")
        return None
    
def execute():
    status = False
    config = read_config()
    web_port = config['mapports']['https']
    
    # 判断docker是否拉起bmc
    target_containers_id = get_qemu_container()
    if not target_containers_id:
        return
    
    print("正在连接bmc...")
    while not status:
        status = try_web_access(web_port)
    print("✅ 连接bmc成功!")

def close_qemu():
    target_containers_id = get_qemu_container()
    subprocess.run(
        ["docker", "rm", "-f", target_containers_id],
        check=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    print(f"✅ 容器 {target_containers_id} 已停止")

def testing():
    # 设置环境变量
    os.environ['OPENUBMC_HOST'] = '127.0.0.1'
    os.environ['OPENUBMC_USERNAME'] = 'Administrator'
    os.environ['OPENUBMC_PASSWORD'] = 'Admin@90000'
    os.environ['IPMI_COMMAND'] = 'External'
    config = read_config()
    os.environ['HTTPS_PORT'] = str(config['mapports']['https'])
    os.environ['SSH_PORT'] = str(config['mapports']['ssh'])
    os.environ['IPMI_PORT'] = str(config['mapports']['ipmi'])

    print("执行 Robot Framework 测试...")
    process = subprocess.Popen(
        ["robot", "-A", "test_lists/QEMU_CI", "redfish/"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    # 实时打印输出
    for line in process.stdout:
        print(line, end="")
    
    process.wait()
    if process.returncode != 0:
        print(f"❌ 测试失败！错误：{process.stderr.read()}")
        close_qemu()
        exit(1)
    print("✅ 测试成功")
    close_qemu()

def install_dependency():
    # 安装tox工具
    try:
        cmd = "sudo apt-get install -y tox"
        subprocess.run(
            shlex.split(cmd),
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        print("✅ tox 安装成功")
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装失败: {e.stderr}")
        sys.exit(1)
    except FileNotFoundError:
        print("❌ 找不到apt-get命令，请确保在Debian/Ubuntu系统上运行")
        sys.exit(1)

    # 安装requirements里面的依赖项
    try:
        subprocess.run(
            ["pip", "install", "-r", "requirements.txt"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        print("✅ 依赖安装成功！")
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败！错误信息：\n{e.stderr}")
        sys.exit(1)


if __name__ == "__main__":
    install_dependency()
    execute()
    testing()
